#pragma once

#include "DispatchImpl.h"

template<class T>
class CPtrDispatchT : public CDispatchImpl
{
public:
	CPtrDispatchT() 
		: m_p(NULL)
	{}

	virtual ~CPtrDispatchT() 
	{
		if (m_p)
			delete m_p;
	}

	T*& GetPtr()
	{
		return m_p;
	}

 	STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
		LCID lcid, DISPID* rgdispid)
	{
		if (_tcscmp(*rgszNames, _T("getPtr")) == 0)
		{
			*rgdispid = 1;
			return S_OK;
		}
		
		return E_FAIL;
	}
	
	STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid,
		LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult,
		EXCEPINFO* pexcepinfo, UINT* puArgErr)
	{
		if (dispidMember == 1 && pdispparams->cArgs == 1)
		{
			pdispparams->rgvarg[0].vt = VT_BYREF;
			pdispparams->rgvarg[0].byref = &m_p;

			if (pvarResult)
			{
				pvarResult->vt = VT_BOOL;
				pvarResult->boolVal = VARIANT_TRUE;
			}
			return S_OK;
		}
		return E_FAIL;
	}
	
private:
	ULONG m_RefCount;

	T* m_p;
};